import {constantRoutes} from "@/router";
import Layout from "@/views/layout/index.vue"
import {Module } from 'vuex'
import {RouteRecordRaw} from 'vue-router'
import {getUserRouters} from "@/api";
const SET_MENU = 'SET_MENU'
const SET_ROUTE = 'SET_ROUTE'
interface PermissionState {
    addRoutes?: RouteRecordRaw[];
    routes?: RouteRecordRaw[];
    menus?: RouteRecordRaw[];
}
function filterSyncMenu( routes: RouteRecordRaw[],root=false){
    for (let i = 0; i < routes.length; i++) {
        // eslint-disable-next-line
        let route = routes[i]
        if(root&&route.children?.length===1 ){
            const child: any = route.children[0]
            if(child.meta && child.meta.isRoot){
                if(!child.path.startsWith("/")){
                    child.path = route.path+ '/' + child.path
                }
                routes[i] = child
            }
        }
        if(route.children){
            filterSyncMenu(route.children)
        }
    }
}
function loadComponent(component: string) {
    return ()=>import(`@/views/${component}.vue`)
}
function filterSyncRoutes(routes: RouteRecordRaw[]) {
    routes.forEach(route=>{
        if((route.component as any) === 'layout'){
            route.component = Layout
        }
        if(typeof route.component  === "string"){
            route.component = loadComponent(route.component)
        }
        if(route.children){
            filterSyncRoutes(route.children)
        }
    })
}
const permission: Module<PermissionState,any> = {
    state:{
       addRoutes:[],
       routes:[],
       menus: []
    },
    mutations:{
        [SET_MENU](state,menus: []){
            state.menus = menus
        },
        [SET_ROUTE](state,routes: []){
            state.addRoutes = routes
            state.routes = constantRoutes.concat(routes)
        }
    },
    actions:{
        async GenerateRoutes({commit}) {
           const {data : routes }  = await getUserRouters()
            const menus = JSON.parse(JSON.stringify(constantRoutes.concat(routes)));
            filterSyncMenu(menus, true)
            filterSyncRoutes(routes)
            commit(SET_ROUTE, routes)
            commit(SET_MENU, menus)
            return routes
        }
    },
}
export default permission
